/*
 * @Author: your name
 * @Date: 2020-09-01 11:25:18
 * @LastEditTime: 2020-09-01 11:38:35
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: /express/src/controller/CrowllerController.ts
 */
import fs from 'fs';
import path from 'path';
import { Request, Response, NextFunction } from 'express';
import { controller, get, use} from './decorator';
import Crowller from '../utils/crowller';
import Analyzer from '../utils/moke/analyzer';
import { getResponseData } from '../utils/util';

interface BodyRequest extends Request {
  body: { [key: string]: string | undefined };
}

const checkLogin = (req:Request, res:Response, next:NextFunction) => {
  const isLogin = req.session ? req.session.login : false;
  if(isLogin) {
    next();
  }else {
    res.json(getResponseData(null, '请先登录'));
  }
}

@controller
class CrowllerController {
  @get('/getData')
  @use(checkLogin)
  getData(req: BodyRequest, res: Response) {
    const secret = 'x3b174jsx';
    const url = `http://www.dell-lee.com/typescript/demo.html?secret=${secret}`;
    const writeFilePath = '../../data/course.json'
    const analyzer = Analyzer.getInstance();
    new Crowller(url, writeFilePath, analyzer);
    res.json(getResponseData(true));
  }
  @get('/showData')
  @use(checkLogin)
  showData(req: BodyRequest, res: Response) {
    try {
      const position = path.resolve(__dirname, '../../data/course.json');
      const result = fs.readFileSync(position, 'utf8');
      res.json(getResponseData(JSON.parse(result)));
    } catch (e) {
      res.json(getResponseData(false, '数据不存在'));
    }
  }
}
